<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <base-table-card>
      <template #header-left>
        <el-tabs v-model="searchParams.authStatus" @tab-change="loadGetTableData">
          <el-tab-pane label="正常" name="NORMAL" />
          <el-tab-pane label="已取消" name="CANCEL" />
        </el-tabs>
      </template>

      <template #header-right>
        <el-button type="primary" v-if="searchParams.authStatus != 'CANCEL'" @click="handleBatchSubmit"
          >一键提审</el-button
        >
      </template>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <template #logoUrl="{ row }">
          <el-avatar :src="row.logoUrl" />
        </template>

        <template #menu="{ row }">
          <ActionBar :row="row" :max-inline="2" :actions="buildRowActions" />
        </template>
      </avue-crud>
    </base-table-card>
    <base-dialog
      v-model="reasonVisible"
      title="查看失败原因："
      width="520px"
      :close-on-click-modal="false"
      :show-footer="false"
    >
      <div style="text-align: center">
        {{ reasonText }}
        <!-- <el-input v-model="reasonText" type="textarea" :rows="6" readonly placeholder="这里显示返回的失败原因。" /> -->
      </div>
    </base-dialog>
    <base-dialog
      v-model="logVisible"
      title="操作日志："
      width="900px"
      :close-on-click-modal="false"
      :show-footer="false"
    >
      <el-table :data="logRows">
        <el-table-column prop="idx" label="序号" width="80" />
        <el-table-column prop="time" label="操作时间" width="200" />
        <el-table-column prop="user" label="操作人员" width="120" />
        <el-table-column prop="action" label="操作内容" width="160" />
        <el-table-column prop="detail" label="详情" />
      </el-table>
    </base-dialog>
  </base-container>
</template>

<script setup>
  import Option from "@/crudOption/channel/miniProgram.js";
  import ActionBar from "@/components/ActionBar/ActionBar.vue"; // 你的 ActionBar 组件路径
  import { createBuildMiniProgramActions } from "@/crudOption/channel/miniProgramAction.js";
  import { ElMessageBox } from "element-plus";
  const reasonVisible = ref(false);
  const reasonText = ref(""); // 接口返回的失败原因

  function openReason(row) {
    reasonText.value = row.failReason || "暂无失败原因";
    reasonVisible.value = true;
  }
  const logVisible = ref(false);
  const logRows = ref([]);

  async function openLog(row) {
    // 这里调用接口获取日志数据，然后赋值给 logRows
    const res = await Api.channel.GetLogList({ id: row.id });
    logRows.value = res.data || [];
    logVisible.value = true;
  }

  // 操作确认函数
  async function confirmFirstSubmit(row) {
    try {
      await ElMessageBox.confirm(`确定要首次提审【${row.miniName}】吗？`, "提示");
      // TODO: 调用首次提审 API
      await Api.channel.FirstSubmitVersion({ id: row.id, type: "KUAISHOU" });
      // ElMessage.success("首次提审成功");
      loadGetTableData();
    } catch {
      // 用户取消或操作失败
    }
  }

  async function confirmResubmit(row) {
    try {
      await ElMessageBox.confirm(`确定要重新提审【${row.miniName}】吗？`, "提示");
      // TODO: 调用重新提审 API
      await Api.channel.ReAuditVersion({ id: row.id, type: "KUAISHOU" });
      // ElMessage.success("重新提审成功");
      loadGetTableData();
    } catch {
      // 用户取消或操作失败
    }
  }

  async function confirmSubmit(row) {
    try {
      await ElMessageBox.confirm(`确定要提审【${row.miniName}】吗？`, "提示");
      // TODO: 调用提审 API
      await Api.channel.LaunchVersion({ id: row.id, type: "KUAISHOU" });
      // ElMessage.success("提审成功");
      loadGetTableData();
    } catch {
      // 用户取消或操作失败
    }
  }

  async function confirmRollback(row) {
    try {
      await ElMessageBox.confirm(`确定要回滚【${row.miniName}】吗？`, "提示");
      // TODO: 调用回滚 API
      await Api.channel.RollbackVersion({ id: row.appId, type: "KUAISHOU" });
      // ElMessage.success("回滚成功");
      loadGetTableData();
    } catch {
      // 用户取消或操作失败
    }
  }

  async function contactCustomer(row) {
    try {
      // 调用联系客户接口
      const res = await Api.channel.ContactCustomer({
        id: row.id,
        type: "KUAISHOU", // 快手小程序
      });

      if (res.code === "200" && res.data) {
        const { customerName, customerContactName, customerContactPhone } = res.data;
        const contactInfo = customerContactPhone
          ? `${customerName}（${customerContactName}）：${customerContactPhone}`
          : `${customerName}：联系电话暂未提供`;

        ElMessageBox.alert(contactInfo, "联系客户", {
          confirmButtonText: "确定",
          type: "info",
        });
      }
    } catch (error) {
      console.error("联系客户接口调用失败:", error);
    }
  }

  // 一键提审功能
  async function handleBatchSubmit() {
    try {
      await ElMessageBox.confirm("确定将所有快手小程序都更新至最新版本吗？", "提示", {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      });

      // TODO: 调用一键提审接口
      // await Api.channel.BatchSubmitKuaiShouMiniPrograms();

      $msg.success("一键提审操作已提交，正在处理中...");

      // 刷新列表数据
      loadGetTableData();
    } catch {
      // 用户取消操作
      console.log("用户取消了一键提审操作");
    }
  }

  // 生成操作按钮配置
  const buildRowActions = createBuildMiniProgramActions({
    fns: {
      confirmFirstSubmit,
      confirmResubmit,
      confirmSubmit,
      confirmRollback,
      openReasonDialog: openReason,
      openLogDialog: openLog,
      contactCustomer,
    },
    denyStrategy: "hide", // 未授权时隐藏按钮
  });

  onMounted(() => {
    // 获取表格数据
    loadGetTableData();
    loadGetNewVersion();
  });

  async function loadGetNewVersion() {
    const res = await Api.channel.GetMiniProgramNewVersion({ miniType: "KUAISHOU" });
    console.log(res);
  }

  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.channel.GetMiniProgramList,
    search: { miniType: "KUAISHOU", authStatus: "NORMAL" },
    getParamsFormat: params => {
      // 授权时间
      if (params.authorizeTime && params.authorizeTime.length === 2) {
        params.authTimeBegin = params.authorizeTime[0] + " 00:00:00";
        params.authTimeEnd = params.authorizeTime[1] + " 23:59:59";
        delete params.authorizeTime;
      }
      // 提审时间
      if (params.submitTime && params.submitTime.length === 2) {
        params.auditTimeBegin = params.submitTime[0] + " 00:00:00";
        params.auditTimeEnd = params.submitTime[1] + " 23:59:59";
        delete params.submitTime;
      }
      // 返回查询参数
      return params;
    },
    add: Api.customer.AddCustomer,
    edit: Api.customer.UpdateCustomer,
  });

  // 获取 搜索配置 和 表格配置
  const { searchOption, tableOption } = Option("KUAISHOU");
</script>

<style lang="scss" scoped></style>
